#include "general_io.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>


void copy_file(const char *src_path, const char *dest_path)
{
    printf("复制文件[%s]到文件[%s]\n", src_path, dest_path);

    int src_fd = open(src_path, O_RDONLY);
    if (src_fd == -1) {
        puts("打开原文件异常");
        exit(-1);
    }

    // 以只写权限打开文件，若文件不是自己创建的，则报错，文件权限为：rw_rw___
    int dest_fd = open(dest_path, O_WRONLY | O_CREAT | O_EXCL | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
    if (dest_fd == -1) {
        perror("打开目的文件异常");
        exit(-1);
    }

    char *buf[4096];
    ssize_t num_read;
    while ((num_read = read(src_fd, buf, sizeof(buf))) > 0) 
        write(dest_fd, buf, num_read);

    if (num_read == -1) {
        const char * err_msg = strerror(errno);
        printf("读取原文件异常，错误信息：%s\n", err_msg);
        exit(-1);
    }

    close(src_fd);
    close(dest_fd);

    puts("复制完毕");

}

void test_general_io()
{
    copy_file("/home/nerve-impulse/programming/linux-programming/test/合并模板.docx", 
        "/home/nerve-impulse/programming/linux-programming/test/合并模板copy.docx");
}
